<template>
    <div class="order-container">
        <div class="header">
            <h1>再生道订单查询系统</h1>
            <p class="slogan">实时追踪每一笔环保订单</p>
        </div>
        
        <div class="order-box">
            <div class="station-section">
                <h3><i class="el-icon-office-building"></i> 回收站订阅</h3>
                <el-input 
                    v-model="stationId" 
                    placeholder="请输入要监控的回收站ID"
                    prefix-icon="el-icon-monitor"
                    class="station-input"
                    clearable
                >
                    <el-button 
                        slot="append" 
                        type="success" 
                        @click="subscribeToStation(stationId)"
                    >监控站点</el-button>
                </el-input>
            </div>

            <div class="order-section">
                <div class="order-list">
                    <h3><i class="el-icon-document"></i> 订单记录</h3>
                    <el-input 
                        v-model="orderMessages"
                        type="textarea"
                        :rows="12"
                        readonly
                        class="order-history"
                    ></el-input>
                </div>

                <div class="statistics-box">
                    <h3><i class="el-icon-data-analysis"></i> 数据统计</h3>
                    <div class="stat-cards">
                        <el-card shadow="hover">
                            <div class="stat-item">
                                <span class="label">今日订单</span>
                                <span class="value">{{ todayOrders }}</span>
                            </div>
                        </el-card>
                        <el-card shadow="hover">
                            <div class="stat-item">
                                <span class="label">总回收量(kg)</span>
                                <span class="value">{{ totalWeight }}</span>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import mqtt from 'mqtt';
import { onMounted, ref } from 'vue';
import { Message } from 'element-ui';

// MQTT客户端配置
var client: mqtt.MqttClient
const clientId = 'mqtt_' + Math.random().toString(16).substr(2, 8)
const url = 'ws://127.0.0.1/mqtt'
const options = {
    port: 8083,
    keepalive: 60,
    clientId: clientId,
    protocolId: 'MQTT',
    protocolVersion: 4 as 4,
    clean: true,
    connectTimeout: 30 * 1000,
    will: {
        topic: 'station',
        payload: '监控断开连接',
        qos: 0,
        retain: false
    },
}

// 创建MQTT连接
client = mqtt.connect(url, options)

// 页面关闭前断开连接
window.onbeforeunload = () => {
    client.end()
    Message.success('已断开监控')
    return ('ok')
}

// 响应式数据
const orderMessages = ref("")
const stationId = ref("")
const todayOrders = ref(0)
const totalWeight = ref(0)

// 订阅站点
function subscribeToStation(id: string) {
    if (!id) {
        Message.warning('请输入站点ID')
        return
    }
    
    const topic = 'station/' + id
    client.subscribe(topic, { qos: 0 }, (error, granted) => {
        if (!error) {
            Message.success(`成功订阅站点: ${id}`)
            // 发送订阅提示
            orderMessages.value += `\n${'='.repeat(50)}\n📡 开始监控站点 ${id}\n${'='.repeat(50)}\n`
        } else {
            Message.error(`订阅失败: ${error}`)
            console.error(`订阅错误: ${error}`)
        }
    })
}

// 接收订单消息
function receiveOrders() {
    client.on('message', (topic, message) => {
        try {
            const orderData = JSON.parse(message.toString())
            // 更新订单记录
            const formattedMessage = `
时间: ${new Date().toLocaleString()}
订单号: ${orderData.orderId}
重量: ${orderData.weight}kg
类型: ${orderData.type}
状态: ${orderData.status}
${'-'.repeat(30)}
`
            orderMessages.value += formattedMessage

            // 更新统计数据
            if (isToday(orderData.createTime)) {
                todayOrders.value++
            }
            totalWeight.value += Number(orderData.weight)
        } catch (e) {
            console.error('消息格式错误:', e)
        }
    })
}

// 判断是否为今天的订单
function isToday(dateStr: string): boolean {
    const today = new Date()
    const orderDate = new Date(dateStr)
    return today.toDateString() === orderDate.toDateString()
}

// 连接相关函数
function connect() {
    client.on('connect', () => {
        console.log('连接状态：' + client.connected)
        Message.success('监控服务连接成功')
    })
}

function connectError() {
    client.on('error', (err) => {
        console.log('连接错误: ', err)
        Message.error('监控连接发生错误')
        client.end()
    })
}

function reconnect() {
    client.on('reconnect', () => {
        console.log('重连中...')
        Message.info('正在重新连接监控服务...')
    })
}

// 生命周期钩子
onMounted(() => {
    connect()
    connectError()
    reconnect()
    receiveOrders()
})
</script>

<style scoped>
.order-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    min-height: 100vh;
    background-color: #f0f9eb;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
}

.header h1 {
    color: #67c23a;
    font-size: 2.5em;
    margin-bottom: 10px;
}

.slogan {
    color: #606266;
    font-size: 1.2em;
    font-style: italic;
}

.order-box {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 30px;
}

.station-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f9eb;
}

.station-input {
    max-width: 500px;
}

.order-section {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 20px;
}

.order-list, .statistics-box {
    background: #fafafa;
    padding: 20px;
    border-radius: 10px;
}

h3 {
    color: #67c23a;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

h3 i {
    font-size: 1.2em;
}

.order-history {
    background: white;
}

.stat-cards {
    display: grid;
    gap: 15px;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;
}

.stat-item .label {
    color: #606266;
    font-size: 14px;
    margin-bottom: 8px;
}

.stat-item .value {
    color: #67c23a;
    font-size: 24px;
    font-weight: bold;
}

.el-button {
    border-radius: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .order-container {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .order-box {
        padding: 15px;
    }

    .order-section {
        grid-template-columns: 1fr;
    }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: #67c23a;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #85ce61;
}
</style> 